<template>
  <div class="upload-img-wrap">
    <upload
      :invoice-url="invoiceUrl"
      :disabled="disabled"
      :verification-state="state"
      @returnUrl="getImgUrl"
    />
    <!-- ocr返回信息对比 -->
    <el-dialog
      title="提示"
      :before-close="beforeClose"
      :visible.sync="visible"
      append-to-body
      width="650px"
    >
      <div class="invoice-dialog-return-info-box">
        <el-form
          :model="FormData"
          :rules="formRules"
          ref="FormData"
          label-width="110px">
          <el-form-item
            label="发票号码"
            prop="quantity">
            <el-input
              v-model="FormData.quantity"
              :disabled="isDisabled"
              placeholder="请输入" />
          </el-form-item>
          <el-form-item
            label="发票代码"
            prop="invoiceCode">
            <el-input
              v-model="FormData.invoiceCode"
              :disabled="isDisabled"
              placeholder="请输入" />
          </el-form-item>
          <el-form-item
            label="开票日期"
            prop="invoiceDate">
            <el-date-picker
              value-format="yyyy-MM-dd"
              :disabled="isDisabled"
              v-model="FormData.invoiceDate"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
          <el-form-item
            label="检验码后六位"
            prop="checkCode">
            <el-input
              v-model="FormData.checkCode"
              :disabled="isDisabled"
              placeholder="请输入" />
          </el-form-item>
          <el-form-item
            label="合计金额"
            prop="totalAmount">
            <el-input-number
              placeholder="请输入"
              :disabled="isDisabled"
              :controls="false"
              v-model="FormData.totalAmount"
              :precision="3"
              :step="0.1"
              :max="9999999999999999999.999"
            />
          </el-form-item>
        </el-form>
        <p class="tips-info">
          <el-image
            style="width: 14px; height: 14px; margin: 0 10px;"
            :src="tipsImg"
            fit="cover" />
          {{ tipsInfo }}
        </p>
        <div class="button-box">
          <el-button
            type="primary"
            :disabled="isDisabled"
            @click="toSubmitForm">确定一致，去验证真伪</el-button>
        </div>

      </div>
    </el-dialog>
  </div>
</template>

<script>
import upload from '@/moduleComponents/common/upload'
import { distinguishForOCR, saveInvoiceElement, confirmInvoice } from '@const/beforeSettleApi.js'
import { hasIn } from 'lodash'

export default {
  name: 'UploadImg',
  components: { upload },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    invoiceNo: {
      type: String,
      require: true,
      default: ''
    },
    src: {
      type: String,
      default: ''
    }
  },
  watch: {
    src (val) {
      if (val) {
        this.invoiceUrl = val
        this.state = 4
      } else {
        this.invoiceUrl = ''
      }
    }
  },
  data () {
    return {
      tipsImg: require('@assets/icon/beforeSettle/tips.png'),
      state: 4,
      invoiceUrl: '',
      activeUrl: '',
      visible: false,
      // 发票验证弹窗
      tipsInfo: '请确认以上信息是否与发票一致，如不一致请进行更正',
      isDisabled: false,
      FormData: {
        quantity: '',
        invoiceCode: '',
        invoiceDate: '',
        checkCode: '',
        totalAmount: ''
      },
      formRules: {
        quantity: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 64, message: '请输入1-64个字符', trigger: 'blur' }
        ],
        invoiceCode: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 64, message: '请输入1-64个字符', trigger: 'blur' }
        ],
        invoiceDate: [{ required: true, message: '请选择', trigger: 'blur' }],
        checkCode: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 126, message: '请输入1-126个字符', trigger: 'blur' }
        ],
        totalAmount: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },
  mounted () {
    this.invoiceUrl = this.src
    if (this.src) {
      this.state = 4
    }
  },
  methods: {
    // 关闭弹窗
    beforeClose () {
      if (this.isDisabled) {
        return void this.$message.warning('不可关闭')
      }
      this.visible = false
      this.state = 4
      this.invoiceUrl = ''
      this.$nextTick(() => {
        this.$refs.FormData.clearValidate()
      })
    },
    // 获取图片地址
    getImgUrl (val) {
      this.invoiceUrl = val
      this.state = 1 // 发票验证状态（1查验中，2通过，3失败，4完成）
      this.OCRidentifyInvoice(val)
    },
    //   确定提交后，form不可在编辑
    toSubmitForm () {
      this.$refs.FormData.validate(valid => {
        if (valid) {
          if (this.FormData.quantity !== this.invoiceNo) {
            return void this.$message.warning('发票号不对')
          }
          this.isDisabled = true // 表单禁用
          let data = {
            ...this.FormData,
            invoiceNo: this.FormData.quantity, // 发票url
            totalPriceTax: this.FormData.totalAmount, // 发票url
            invoiceUrl: this.invoiceUrl, // 发票url
            // saleOrderId: this.id, // 主单id
            sourceType: 1// 后补影像1
            // type: this.$route.query.type // 缓存页面type
          }
          this.tipsInfo = '正在验证发票真伪，请耐心等候…系统即将返回结果'
          this.$axios({
            method: 'post',
            url: saveInvoiceElement,
            data: data
          })
            .then(res => {
              if (res.data.payload.exsit) {
                if (res.data.payload.msg) {
                  // 一定是验证通过
                  this.state = 2 // 验证通过，两秒后变成完成状态4
                  setTimeout(() => {
                    this.state = 4
                  }, 2000)

                  this.visible = false
                } else {
                  this.verifyAuthenticity(data) // 验证发票真伪
                }
              }
            })
            .catch(() => {
              this.isDisabled = false
            })
        }
      })
    },
    // 校验真伪
    verifyAuthenticity (data) {
      this.$axios({
        method: 'post',
        url: confirmInvoice,
        data: data
      })
        .then(res => {
          if (res.data.code === '0') {
            let status = Object.keys(res.data.payload)[0] // 0通过  1失败
            if (status === 0) {
              this.state = 2 // 验证通过，两秒后变成完成状态4
              setTimeout(() => {
                this.state = 4
              }, 2000)
            } else {
              this.state = 3 // 验证失败，两秒后清空图片，重新上传
              // setTimeout(() => {
              //   this.invoiceUrl = ''
              // }, 2000)
            }
          }
        })
        .catch(() => {
          this.isDisabled = false
        })
    },
    // OCR识别发票
    OCRidentifyInvoice (url) {
      this.$axios({
        method: 'post',
        url: distinguishForOCR,
        data: {
          imgUrl: url
        }
      })
        .then(res => {
          if (res.data.code !== '0') return
          const resData = hasIn(res, 'data.payload') ? res.data.payload : {}
          if (typeof resData === 'object') {
          // if (resData.quantity !== this.invoiceNo) {
          //   this.invoiceUrl = ''
          //   this.state = 4 // 发票验证状态（1查验中，2通过，3失败，4完成）
          //   return void this.$message.warning('发票号不对')
          // }
            this.visible = true // OCR返回了发票数据
            this.tipsInfo = '请确认以上信息是否与发票一致，如不一致请进行更正'
            this.FormData = hasIn(res, 'data.payload.invoiceCode') ? res.data.payload : {}
          }
          if (typeof resData === 'string') {
            this.$message.warning('请上传真实发票')
            this.invoiceUrl = ''
            this.state = 4 // 发票验证状态（1查验中，2通过，3失败，4完成）
          }
        })
        .catch((err) => {
          console.log(err)
          this.invoiceUrl = ''
          this.state = 4 // 发票验证状态（1查验中，2通过，3失败，4完成）
        })
    }
  }
}
</script>

<style lang="less">
.invoice-dialog-return-info-box {
  width: 540px;
  margin: 0 auto;
  margin-top: 30px;
  padding-bottom: 30px;
  .el-input-number--medium {
    width: 428px;
  }
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 428px;
  }
  .el-select {
    width: 428px;
  }
  // 提示信息样式
  .tips-info {
    margin: 0 auto;
    background: #e6f7ff;
    color: rgba(0, 0, 0, 0.65);
    font-size: 14px;
    width: 475px;
    height: 40px;
    border: 1px solid #2371c5;
    border-radius: 5px;
    display: flex;
    align-items: center;
  }
  .button-box {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  .el-input-number.is-without-controls .el-input__inner {
    text-align: left;
  }
}
</style>
